package com.sanqing.iframe;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import com.sanqing.dao.Dao;
import com.sanqing.iframe.BookSearchFrame.TableListener;
import com.sanqing.model.BookInfo;
import com.sanqing.model.Item;
import com.sanqing.model.MapPz;
import com.sanqing.model.Operator;
import com.sanqing.model.PopupMenu;

public class ReserveIFrame extends JInternalFrame {
	private int Number = 0;
	private int Number1 = Dao
			.selectReserve(
					"select * from tb_reserve where readerISBN='" + BookLoginIFrame.getOperator().getISBN() + "'")
			.size();;
	private final BorderLayout borderLayout;
	private final BorderLayout borderLayout_1;
	private final JScrollPane scrollPane;
	private final JPanel mainPanel;
	private final JPanel reserveSearchPanel;
	private final JPanel reservePanel;
	private final GridLayout gridLayout;
	private final GridLayout gridLayout1;
	private final JLabel reserveLabel;
	private final JTextField reserveText;
	private final JButton searchButton;
	private final JButton deleteButton;
	private final JButton reserveButton;
	private final JButton closeButton;
	private String reserveBookISBN;
	private int canReserveBook;
	private int getSelectTableRow = -1;
	private static int canreserveBook;
	private JTable table;
	private Object[][] results;
	private Object[][] Results;
	private String[] columnNames;
	private PopupMenu popupMenu;
	
	private Map<String, Boolean> mapISBN = new HashMap<>();

	private Object[][] getFileStates(List list) {
		String[] columnNames = { "图书编号", "图书类别", "图书名称", "作者", "译者", "出版商", "出版日期", "价格", "图书数量" };
		Object[][] results = new Object[list.size()][columnNames.length];
		for (int i = 0; i < list.size(); i++) {
			BookInfo bookinfo = (BookInfo) list.get(i);
			results[i][0] = bookinfo.getISBN();
			// 获取图书类型名称
			Integer typeId = bookinfo.getTypeid();
			// System.out.println(typeId);
			String bookTypeName = MapPz.getIdToName().get(typeId);
			// System.out.println(bookTypeName);
			results[i][1] = bookTypeName;
			results[i][2] = bookinfo.getBookname();
			results[i][3] = bookinfo.getWriter();
			results[i][4] = bookinfo.getTranslator();
			results[i][5] = bookinfo.getPublisher();
			results[i][6] = bookinfo.getDate();
			results[i][7] = bookinfo.getPrice();
			results[i][8] = bookinfo.getNumber();
		}
		return results;
	}

	public ReserveIFrame() {
		super();
		// Results=new Object[1][];

		borderLayout = new BorderLayout();
		getContentPane().setLayout(borderLayout);
		setIconifiable(true);
		setClosable(true);
		setTitle("预约图书");
		setBounds(100, 100, 593, 406);
		mainPanel = new JPanel();
		borderLayout_1 = new BorderLayout();
		borderLayout_1.setVgap(5);
		mainPanel.setLayout(borderLayout_1);
		mainPanel.setBorder(new EmptyBorder(5, 10, 5, 10));
		getContentPane().add(mainPanel);
		scrollPane = new JScrollPane();
		mainPanel.add(scrollPane);

		//
		reserveSearchPanel = new JPanel();
		mainPanel.add(reserveSearchPanel, BorderLayout.NORTH);
		gridLayout = new GridLayout(1, 4);
		gridLayout.setHgap(0);
		reserveSearchPanel.setLayout(gridLayout);
		reserveLabel = new JLabel();
		reserveLabel.setText("图书的ISBN");
		reserveText = new JTextField();
		reserveText.setText("请输入要预约图书的ISBN");
		reserveText.addFocusListener(new reserveTextFocus());
		reserveText.addKeyListener(new reserveTextKey());
		searchButton = new JButton();
		searchButton.setText("添加");
		deleteButton = new JButton();
		deleteButton.setText("删除");
		searchButton.addActionListener(new searchButtonAction());
		deleteButton.addActionListener(new deleteButtonAction());
		reserveSearchPanel.add(reserveLabel);
		reserveSearchPanel.add(reserveText);
		reserveSearchPanel.add(searchButton);
		reserveSearchPanel.add(deleteButton);

		reservePanel = new JPanel();
		mainPanel.add(reservePanel, BorderLayout.SOUTH);
		gridLayout1 = new GridLayout(1, 2);
		reservePanel.setLayout(gridLayout1);
		reserveButton = new JButton();
		closeButton = new JButton();
		reserveButton.setText("预约");
		closeButton.setText("关闭");
		reserveButton.addActionListener(new reserveButtonAction());
		closeButton.addActionListener(new closeButtonAction());
		reservePanel.add(reserveButton);
		reservePanel.add(closeButton);
	}

	private class reserveTextKey implements KeyListener {

		@Override
		public void keyPressed(KeyEvent e) {
			// TODO Auto-generated method stub

		}

		@Override
		public void keyReleased(KeyEvent e) {
			// TODO Auto-generated method stub
			if (reserveText.getText().length() > 13) {
				reserveText.setText(reserveText.getText().substring(0, 13));
			}
			String a = reserveText.getText();
			for (int i = 0; i < a.length(); i++) {
				int b = a.charAt(i);
				if (!(b <= 57 && b >= 48)) {
					reserveText.setText("");
					break;
				}
			}
		}

		@Override
		public void keyTyped(KeyEvent e) {
			// TODO Auto-generated method stub
			int temp = e.getKeyChar();
			if (reserveText.getText().length() == 13) {
				e.consume();
			} else {
				if (temp == 10) {
				} else if (temp != 46) {
					if (temp != 8) {
						if (temp > 57) {
							e.consume();
						} else if (temp < 48) {
							e.consume();
						}
					}
				} else {
					e.consume();
				}
			}
		}

	}

	private class reserveButtonAction implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent arg0) {
			// TODO Auto-generated method stub

			if (Number == 0) {
				JOptionPane.showMessageDialog(null, "表格中尚未添加任何数据", "提示", JOptionPane.ERROR_MESSAGE);
			} else if (getSelectTableRow != -1) {
				
				int count=Dao.selectReserve("select * from tb_reserve where bookISBN="+"'"+Results[getSelectTableRow][0]+"'").size();
				if(count>0)
				{
					int confirm = JOptionPane.showConfirmDialog(null, "该ISBN为"+Results[getSelectTableRow][0] +"已有 " + count + " 个人预约，是否继续预约？", "否是",
							JOptionPane.YES_NO_OPTION);
					if (confirm != JOptionPane.YES_OPTION) {
						return;
					}
				}
				Dao.InsertBorrow("insert into tb_reserve(readerISBN,bookISBN)values(" + "'"
						+ BookLoginIFrame.getOperator().getISBN() + "','" + (String) Results[getSelectTableRow][0]
						+ "')");
				deleteTableRecord();
				JOptionPane.showMessageDialog(null, "预约成功", "提示", JOptionPane.PLAIN_MESSAGE);
				// Number1++;

			} else {
				
				for (int i = 0; i < Number; i++) {
					int count=Dao.selectReserve("select * from tb_reserve where bookISBN="+"'"+Results[i][0]+"'").size();
					if(count>0)
					{
						int confirm = JOptionPane.showConfirmDialog(null, "该ISBN为"+Results[i][0] +"已有 " + count + " 个人预约，是否继续预约？", "否是",
								JOptionPane.YES_NO_OPTION);
						if (confirm != JOptionPane.YES_OPTION) {
							return;
						}
					}
					Dao.InsertBorrow("insert into tb_reserve(readerISBN,bookISBN)values(" + "'"
							+ BookLoginIFrame.getOperator().getISBN() + "','" + (String) Results[i][0] + "')");
					// Number1++;
				}
				Results = new Object[0][0];
				results = new Object[0][0];
				Number = 0;
				mapISBN = new HashMap<>();
				tableE();
				JOptionPane.showMessageDialog(null, "预约成功", "提示", JOptionPane.PLAIN_MESSAGE);
				// reserveText.setText("请输入要预约图书的ISBN");
			}
			if (canReserveBook == Number1) {
				JOptionPane.showMessageDialog(null, "当前已是最大预约数，不可再预约", "提示", JOptionPane.WARNING_MESSAGE);
				doDefaultCloseAction();
			}
			reserveText.setText("请输入要借阅书的ISBN");
		}
	}

	private class closeButtonAction implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent arg0) {
			// TODO Auto-generated method stub
			doDefaultCloseAction();// 关闭窗体
		}

	}

	private class deleteButtonAction implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent arg0) {
			// TODO Auto-generated method stub
			Number1--;
			deleteTableRecord();
		}

	}

	private class searchButtonAction implements ActionListener {// 查找并且添加

		@Override
		public void actionPerformed(ActionEvent arg0) {
			// TODO Auto-generated method stub
			reserveBookISBN = reserveText.getText();
			results = getFileStates(Dao.selectBookInfo(reserveBookISBN));
			canReserveBook = 1;
			if (BookLoginIFrame.getOperator().getZj() == 2)
				canReserveBook = 2;
			int bookCount = 0;
			if (results.length != 0) {
				bookCount = (int) results[0][8];
			}
			int book = Dao.selectBorrow("select * from tb_borrow where bookISBN='" + reserveBookISBN + "' and isback=0")
					.size()
					+ Dao.selectReserve("select * from tb_reserve where bookISBN='" + reserveBookISBN + "'").size();
			int reader = Dao
					.selectBorrow("select * from tb_borrow where isback=0 and readerISBN='"
							+ BookLoginIFrame.getOperator().getISBN() + "'")
					.size()
					+ Dao.selectReserve("select * from tb_reserve where readerISBN='"
							+ BookLoginIFrame.getOperator().getISBN() + "'").size();
			int whetherReserveBook = Dao.selectBorrow("select * from tb_borrow where readerISBN='"
					+ BookLoginIFrame.getOperator().getISBN() + "' and bookISBN='" + reserveBookISBN + "' and isback=0")
					.size();
			int bookReserve = Dao.selectReserve("select * from tb_reserve where bookISBN='" + reserveBookISBN
					+ "' and readerISBN='" + BookLoginIFrame.getOperator().getISBN() + "'").size();
			// System.out.println(reader);
			if (results.length == 0) {
				if (reserveText.getText().equals("请输入要预约图书的ISBN")) {
					JOptionPane.showMessageDialog(null, "请输入要预约图书的ISBN", "提示", JOptionPane.WARNING_MESSAGE);
				} else
					JOptionPane.showMessageDialog(null, "未找到这本图书", "提示", JOptionPane.ERROR_MESSAGE);
			} else if (whetherReserveBook >= 1) {
				JOptionPane.showMessageDialog(null, "这本书已经被借过了，且尚未归还", "提示", JOptionPane.ERROR_MESSAGE);
			} else if (canReserveBook == Number1) {
				JOptionPane.showMessageDialog(null, "表中添加的已是可预约的最大总量", "提示", JOptionPane.ERROR_MESSAGE);
			} else if (Integer.parseInt(BookLoginIFrame.getOperator().getMaxNum()) == reader) {
				JOptionPane.showMessageDialog(null, "当前预约书籍与借阅书籍已达到最大的借书量", "提示", JOptionPane.ERROR_MESSAGE);
				doDefaultCloseAction();
			} else if (Objects.isNull(mapISBN.get(reserveBookISBN)) == false) {
				JOptionPane.showMessageDialog(null, "该书已经添加到表格里面啦", "提示", JOptionPane.ERROR_MESSAGE);
			} else if (bookReserve == 1) {
				JOptionPane.showMessageDialog(null, "这本书你已经被预约过了", "提示", JOptionPane.ERROR_MESSAGE);
			} else if (bookCount > book) {
				JOptionPane.showMessageDialog(null, "这本书尚有存量，不用预约", "提示", JOptionPane.ERROR_MESSAGE);
			} else {
				mapISBN.put(reserveBookISBN, true);
				Results = addResults();
				Number1++;
				tableR();
			}
			reserveText.setText("请输入要预约图书的ISBN");
		}
	}

	 private class CombinedTableListener extends MouseAdapter {
	        @Override
	        public void mouseClicked(MouseEvent e) {
	            if (e.getButton() == MouseEvent.BUTTON1) {
	            	getSelectTableRow = table.getSelectedRow();
	            }
	            // 调用PopupMenu中的TableListener处理右击事件
	            else popupMenu.getTableListener().mouseClicked(e);
	        }
	    }

	private class reserveTextFocus implements FocusListener {

		@Override
		public void focusGained(FocusEvent arg0) {
			// TODO Auto-generated method stub
			if (reserveText.getText().equals("请输入要预约图书的ISBN"))
				reserveText.setText("");
		}

		@Override
		public void focusLost(FocusEvent arg0) {
			// TODO Auto-generated method stub
			if (reserveText.getText().equals(""))
				reserveText.setText("请输入要预约图书的ISBN");
		}

	}

	private Object[][] addResults() {
		Object[][] Results;
		Number++;
		Results = new Object[Number][];
		for (int i = 0; i < Number - 1; i++)
			Results[i] = this.Results[i];
		Results[Number - 1] = results[0];
		return Results;
	}

	private void tableR() {
		columnNames = new String[] { "图书编号", "图书类别", "图书名称", "作者", "译者", "出版商", "出版日期", "价格", "图书数量" }; // 正确声明
		 table = new JTable(Results, columnNames) {
             @Override
             public boolean isCellEditable(int row, int column) {
                 return false; // 所有单元格都不可编辑
             }
         };
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		scrollPane.setViewportView(table);
		popupMenu = new PopupMenu(table, this, columnNames);
		table.addMouseListener(new CombinedTableListener());
	}

	private void tableE() {
		columnNames = new String[0]; // 正确声明
		 table = new JTable(Results, columnNames) {
             @Override
             public boolean isCellEditable(int row, int column) {
                 return false; // 所有单元格都不可编辑
             }
         };
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		scrollPane.setViewportView(table);
		table.addMouseListener(new CombinedTableListener());
	}

	private void deleteTableRecord() {
		if (getSelectTableRow != -1) {
			Object[][] results = new Object[Number - 1][];
			mapISBN.remove((String) Results[getSelectTableRow][0]);
			for (int i = 0; i < getSelectTableRow; i++)
				results[i] = Results[i];
			for (int i = getSelectTableRow + 1; i < Number; i++) {
				results[i - 1] = Results[i];
			}
			Results = results;
			Number--;
			getSelectTableRow = -1;
			if (Number != 0)
				tableR();
			else
				tableE();

		} else {
			JOptionPane.showMessageDialog(null, "未选择表中的数据或者表中没有数据", "提示", JOptionPane.ERROR_MESSAGE);
		}
	}
}
